Partial Public Class pages_Seriess_default : Inherits CPage

#Region "Data"
    Public ReadOnly Property [Seriess]() As CSeriesList
        Get
            Return CSeries.Cache
        End Get
    End Property
#End Region

#Region "Event Handlers - Page"
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
        'Textbox behaviour
        CTextbox.OnReturnPress(txtFrom, btnGo1)
        CTextbox.OnReturnPress(txtTo, btnGo2)
        CTextbox.OnReturnPress(txtStopRatio, btnGo3)
        CTextbox.OnReturnPress(txtInvestRatio, btnGo4)
        CTextbox.OnReturnPress(txtMinAdx, btnGo5)
        CTextbox.OnReturnPress(txtMinAdxChange, btnGo6)
        CTextbox.OnReturnPress(txtLeverage, btnGo7)
        CTextbox.OnReturnPress(txtStart, btnGo8)


        'Restore state
        CTextbox.SetDate(txtFrom, CData.FROM_DATE)
        CTextbox.SetDate(txtTo, CData.TO_DATE)
        txtStart.Text = "$" & CSimulation.START.ToString("n0")
        CTextbox.SetNumber(txtInvestRatio, CSimulation.INVEST)
        CTextbox.SetNumber(txtStopRatio, CData.STOP_RATIO)
        CTextbox.SetNumber(txtMinAdx, CData.MIN_ADX)
        CTextbox.SetNumber(txtMinAdxChange, CData.MIN_ADX_CHANGE)
        CTextbox.SetNumber(txtLeverage, CSimulation.LEVERAGE)
        chkAdxInvestMore.Checked = CSimulation.INVEST_MORE_IF_ADX_IS_HIGHER
        chkInvestRepeatedly.Checked = CSimulation.KEEP_INVESTING_WHILE_BUY
        chkStopWhenSeedGone.Checked = CSimulation.STOP_WHEN_SEED_CAPITAL_GONE
        chkCancelOpenTrades.Checked = CSimulation.CANCEL_OPEN_TRADES_IF_STOP


        'Display 
        ctrlSeriess.Display(Me.Seriess)

        Dim s As CSeriesList = CSession.SelectedSeries


        litLeverage.Text = CSimulation.LEVERAGE.ToString()
        litStart.Text = CSimulation.START.ToString("C0")
        litActiveSeries.Text = CSession.SelectedSeriesIds.Count.ToString()
        'litTotalPool.Text = s.PoolLeveraged.ToString("C")
        litProfit.Text = s.TotalProfit.ToString("C")
        If s.AnnualisedReturns > 1000 Then
            litAnnRet.Text = (100 * s.AnnualisedReturns).ToString("e1") & " %"
        Else
            litAnnRet.Text = s.AnnualisedReturns.ToString("P")
        End If
        litReturns.Text = s.TotalReturns.ToString("P")
        litAvgExposure.Text = s.AverageTotalExposure().ToString("P")
        If s.ExposureAdjustedNetReturns > 1000 Then
            litExpAdjRet.Text = (100 * s.ExposureAdjustedNetReturns).ToString("e1") & " %"
        Else
            litExpAdjRet.Text = s.ExposureAdjustedNetReturns.ToString("P")
        End If
        litMaxExposure.Text = s.MaxTotalExposure.ToString("P")
        litSimTime.Text = CUtilities.Timespan(s.TimeSpan)
        litFrom.Text = s.MinDate.ToString("d MMM yyyy")
        litTo.Text = s.MaxDate.ToString("d MMM yyyy")
        litFinish.Text = (s.TotalProfit + s.Count * CSimulation.START * CSimulation.LEVERAGE).ToString("C")
        litLow.Text = "$" & s.Low.ToString("n0")
        litHigh.Text = "$" & s.High.ToString("n0")
        litWins.Text = s.WinsPercent.ToString("P0")
        litLosses.Text = s.LossesPercent.ToString("P0")
        litFlat.Text = s.FlatPercent.ToString("P0")

        For i As Integer = 2 To 30
            CDropdown.Add(ddPeriodADX, i.ToString, i)
            CDropdown.Add(ddPeriodDM, i.ToString, i)
            CDropdown.Add(ddPeriodTR, i.ToString, i)
        Next
        CDropdown.SetValue(ddPeriodADX, CData.PERIOD_ADX)
        CDropdown.SetValue(ddPeriodDM, CData.PERIOD_DM)
        CDropdown.SetValue(ddPeriodTR, CData.PERIOD_TR)
    End Sub
    Protected Sub Page_PreRender1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        If Seriess.TotalDays / 365 > 4 Then
            QuarterlyChart()
        ElseIf Seriess.TotalDays > 270 Then
            MonthlyChart()
        Else
            DailyChart()
        End If
    End Sub
#End Region

#Region "Event Handlers - Form"
    Protected Sub chk_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkCancelOpenTrades.CheckedChanged, chkAdxInvestMore.CheckedChanged, chkInvestRepeatedly.CheckedChanged, chkStopWhenSeedGone.CheckedChanged
        CSimulation.INVEST_MORE_IF_ADX_IS_HIGHER = chkAdxInvestMore.Checked
        CSimulation.KEEP_INVESTING_WHILE_BUY = chkInvestRepeatedly.Checked
        CSimulation.STOP_WHEN_SEED_CAPITAL_GONE = chkStopWhenSeedGone.Checked
        CSimulation.CANCEL_OPEN_TRADES_IF_STOP = chkCancelOpenTrades.Checked

        CData.Cache = Nothing
        CSeries.Cache = Nothing
        CSession.SelectedSeries = Nothing
        btnSearch_Click(sender, e)
    End Sub
    Protected Sub btnGo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGo1.Click, btnGo2.Click, btnGo3.Click, btnGo4.Click, btnGo5.Click, btnGo6.Click, btnGo7.Click, btnGo8.Click
        CData.FROM_DATE = CTextbox.GetDate(txtFrom)
        CData.TO_DATE = CTextbox.GetDate(txtTo)
        CData.STOP_RATIO = CTextbox.GetNumber(txtStopRatio)
        CData.MIN_ADX = CTextbox.GetNumber(txtMinAdx)
        CData.MIN_ADX_CHANGE = CTextbox.GetNumber(txtMinAdxChange)

        CSimulation.START = CTextbox.GetMoney(txtStart)
        CSimulation.INVEST = CTextbox.GetNumber(txtInvestRatio)
        CSimulation.LEVERAGE = CTextbox.GetNumber(txtLeverage)

        CData.Cache = Nothing
        CSeries.Cache = Nothing
        Session.Clear()
        btnSearch_Click(sender, e)
    End Sub
    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Response.Redirect(CSitemap.Seriess(ctrlSeriess.Info))
    End Sub
    Protected Sub ddLength_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddPeriodADX.SelectedIndexChanged, ddPeriodDM.SelectedIndexChanged, ddPeriodTR.SelectedIndexChanged
        CData.PERIOD_ADX = CDropdown.GetInt(ddPeriodADX)
        CData.PERIOD_DM = CDropdown.GetInt(ddPeriodDM)
        CData.PERIOD_TR = CDropdown.GetInt(ddPeriodTR)
        CData.Cache = Nothing
        CSeries.Cache = Nothing
        Session.Clear()
        Response.Redirect(Request.RawUrl)
    End Sub
#End Region

#Region "Event Handlers - UserControl"
    Private Sub ctrl_AddClick() Handles ctrlSeriess.AddClick
        Response.Redirect(CSitemap.SeriesAdd())
    End Sub
    Private Sub ctrl_ExportClick() Handles ctrlSeriess.ExportClick
        Seriess.ExportToCsv(Response, "Seriess.csv")
    End Sub
    Private Sub ctrl_ResortClick(ByVal sortBy As String, ByVal descending As Boolean, ByVal pageNumber As Integer) Handles ctrlSeriess.ResortClick
        Response.Redirect(CSitemap.Seriess(New CPagingInfo(0, pageNumber - 1, sortBy, descending)))
    End Sub
#End Region

#Region "Charting"
    Public Sub DailyChart()
        litFreq.Text = " (Daily)"


        Dim ss As CSeriesList = CSession.SelectedSeries

        Dim sb As New StringBuilder
        For Each s As CSeries In ss
            sb.Append("data.addColumn('number', '").Append(s.SeriesName).AppendLine("');")
        Next
        sb.Append("data.addRows(").Append(ss.Dates.Count).AppendLine(");")

        For Each d As DateTime In ss.Dates
            Dim index As Integer = ss.Dates.IndexOf(d)
            'Date
            sb.Append("data.setValue(").Append(index).Append(", 0, '").Append(d.ToString("d MMM yy")).AppendLine("'); ")
            'Total
            Dim total As Double = ss.Totals(index)
            Dim profit As Double = total - ss.Count * CSimulation.LEVERAGE * CSimulation.START
            sb.Append("data.setValue(").Append(index).Append(", 1, ").Append(profit.ToString()).AppendLine("); ")
            'Data
            For Each s As CSeries In ss
                Dim i As CData = s.Datas.GetByDate(d)
                If Not IsNothing(i) Then
                    total = i.SimulatedProfit
                Else
                    Dim temp As DateTime = d
                    While d >= s.From And IsNothing(i)
                        i = s.Datas.GetByDate(temp)
                        temp = temp.AddDays(-1)
                    End While
                    If IsNothing(i) Then
                        total = 0
                    Else
                        total = i.SimulatedProfit
                    End If
                End If
                sb.Append("data.setValue(").Append(index).Append(", ").Append(2 + ss.IndexOf(s)).Append(", ").Append(total.ToString()).AppendLine("); ")
            Next
        Next
        litScript.Text = sb.ToString()
    End Sub
    Public Sub MonthlyChart()
        litFreq.Text = " (Monthly)"

        Dim ss As CSeriesList = CSession.SelectedSeries

        Dim sb As New StringBuilder
        For Each s As CSeries In ss
            sb.Append("data.addColumn('number', '").Append(s.SeriesName).AppendLine("');")
        Next
        sb.Append("data.addRows(").Append(ss.Months.Count).AppendLine(");")

        For Each d As DateTime In ss.Months
            Dim dayIndex As Integer = ss.Dates.IndexOf(d)
            Dim mthIndex As Integer = ss.Months.IndexOf(d)
            'Date
            sb.Append("data.setValue(").Append(mthIndex).Append(", 0, '").Append(d.ToString("d MMM yy")).AppendLine("'); ")
            'Total
            Dim total As Double = ss.Totals(dayIndex)
            Dim profit As Double = total - ss.Count * CSimulation.LEVERAGE * CSimulation.START
            sb.Append("data.setValue(").Append(mthIndex).Append(", 1, ").Append(profit.ToString()).AppendLine("); ")
            'Data
            For Each s As CSeries In ss
                Dim i As CData = s.Datas.GetByDate(d)
                If Not IsNothing(i) Then
                    total = i.SimulatedProfit
                Else
                    Dim temp As DateTime = d
                    While d >= s.From And IsNothing(i)
                        i = s.Datas.GetByDate(temp)
                        temp = temp.AddDays(-1)
                    End While
                    If IsNothing(i) Then
                        total = 0
                    Else
                        total = i.SimulatedProfit
                    End If
                End If
                sb.Append("data.setValue(").Append(mthIndex).Append(", ").Append(2 + ss.IndexOf(s)).Append(", ").Append(total.ToString()).AppendLine("); ")
            Next
        Next
        litScript.Text = sb.ToString()
    End Sub
    Public Sub QuarterlyChart()
        litFreq.Text = " (Quarterly)"

        Dim ss As CSeriesList = CSession.SelectedSeries

        Dim sb As New StringBuilder
        For Each s As CSeries In ss
            sb.Append("data.addColumn('number', '").Append(s.SeriesName).AppendLine("');")
        Next
        sb.Append("data.addRows(").Append(ss.Quarters.Count).AppendLine(");")

        For Each d As DateTime In ss.Quarters
            Dim dayIndex As Integer = ss.Dates.IndexOf(d)
            Dim qtrIndex As Integer = ss.Quarters.IndexOf(d)
            'Date
            sb.Append("data.setValue(").Append(qtrIndex).Append(", 0, '").Append(d.ToString("d MMM yy")).AppendLine("'); ")
            'Total
            Dim total As Double = ss.Totals(dayIndex)
            Dim profit As Double = total - ss.Count * CSimulation.LEVERAGE * CSimulation.START
            sb.Append("data.setValue(").Append(qtrIndex).Append(", 1, ").Append(profit.ToString()).AppendLine("); ")
            'Data
            For Each s As CSeries In ss
                Dim i As CData = s.Datas.GetByDate(d)
                If Not IsNothing(i) Then
                    total = i.SimulatedProfit
                ElseIf s.Length = 0 Then
                    total = 0
                Else
                    Dim temp As DateTime = d
                    While d >= s.From And IsNothing(i)
                        i = s.Datas.GetByDate(temp)
                        temp = temp.AddDays(-1)
                    End While
                    If IsNothing(i) Then
                        total = 0
                    Else
                        total = i.SimulatedProfit
                    End If
                End If
                sb.Append("data.setValue(").Append(qtrIndex).Append(", ").Append(2 + ss.IndexOf(s)).Append(", ").Append(total.ToString()).AppendLine("); ")
            Next
        Next
        litScript.Text = sb.ToString()
    End Sub
#End Region

End Class
